package persistence ;

/**
 * @author idan
 */
public abstract class SingleSessionPersistence implements PersistenceController
{

	private boolean inTransaction ;

	/**
	 * @post there is currently no transaction.
	 */
	public SingleSessionPersistence()
	{
		super() ;
	}

	/**
	 * @see persistence.PersistenceController#commitTransaction()
	 */
	@Override
	public synchronized void commitTransaction() throws RuntimeException
	{
		if (!this.inTransaction)
		{
			throw new RuntimeException("commiting without a transaction") ;
		}
		this.commitToDatabase() ;
		this.inTransaction = false ;
		this.notify() ;
	}

	/**
	 * @see persistence.PersistenceController#startTransaction()
	 */
	@Override
	public synchronized void startTransaction()
	{
		while (this.inTransaction == true)
		{
			try
			{
				this.wait() ;
			}
			catch (InterruptedException e)
			{
				// just keep checking the condition
			}
		}
		this.inTransaction = true ;
	}

	/**
	 * commit changes in this session to the database.
	 * @post the database is synchronized with the memory.
	 */
	protected abstract void commitToDatabase() ;

}
